<template>
  <div class="mod-config">
    <div class="div-e" v-loading="loading">
      <div class="in-t">
        <div class="in-ts"></div>
        <h3>{{isAdd ? "客户新增" : "客户修改"}}</h3>
      </div>
      <el-row>
        <el-col :span="20" :offset="2">
          <el-form :model="addOrUpdateForm" :rules="addOrUpdateFormRules" ref="addOrUpdateFormRefs" label-width="150px">
            <el-form-item  label="企业名称" prop="name">
              <el-input v-model="addOrUpdateForm.name" placeholder="请填写企业名称"></el-input>
            </el-form-item>
            <el-form-item  label="社会统一信用代码" prop="certificateCode">
              <!--              <el-input v-model="addOrUpdateForm.certificateCode" placeholder="请填写社会统一信用代码（18位）" :disabled="!isAdd"></el-input>-->
              <el-input v-model="addOrUpdateForm.certificateCode" placeholder="请填写社会统一信用代码（18位）" ></el-input>
            </el-form-item>
            <el-form-item  label="所在地区" prop="areaId">
              <el-row>
                <el-col :span="6">
                  <el-select v-model="addOrUpdateForm.cityId" placeholder="请选择城市" @change="changeCityOptions" @focus="getRegionalTree">
                    <el-option
                      v-for="item in cityOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="6" :offset="1">
                  <el-select  v-model="addOrUpdateForm.areaId" placeholder="请选择区域">
                    <el-option
                      v-for="item in areaOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="资质证明" prop="">
              <el-upload
                list-type="picture-card"
                :headers="uploadHeader"
                :file-list="uploadFileList"
                :before-upload="handlePicUploadBefore"
                :on-success="handlePicUploadSuccess"
                :on-error="handlePicUploadError"
                :on-remove="handlePicUploadRemove"
                :action="this.$http.adornUrl('/ent/customer/file/upload')"
                accept=".jpg,.png">
                <i class="el-icon-plus"></i>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过800kb</div>
              </el-upload>
            </el-form-item>
            <el-form-item  label="资质项" prop="qualiIdList">
              <div class="select-button-group">
                <el-select  placeholder="请选择/填写企业资质证书信息"
                            v-model="addOrUpdateForm.qualiNames"
                            :remote-method="remoteMethod"
                            value-key = "id"
                            @change="changeQualiOptions"
                            multiple
                            filterable
                            remote
                            default-first-option>
                  <el-option
                    v-for="item in qualiOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item">
                  </el-option>
                </el-select>
                <!--                <el-button type="primary" @click="matchQuali">智能匹配资质项</el-button>-->
              </div>
              <div><span>提示：请按照企业资质证书真实填写，多个以逗号(,)顿号(、)分隔，如:环保工程专业承包三级、钢结构工程专业承包三级,…</span></div>
            </el-form-item>
            <el-form-item  label="联系人" prop="contactsName">
              <el-input v-model="addOrUpdateForm.contactsName" placeholder="请填写联系人姓名"></el-input>
            </el-form-item>
            <el-form-item label="职务" prop="">
              <el-input v-model="addOrUpdateForm.contactsPosition"  placeholder="请填写联系人职务"></el-input>
            </el-form-item>
            <el-form-item  label="联系人电话" prop="">
              <el-input v-model="addOrUpdateForm.contactsMobile" placeholder="请填写联系人手机或固定电话"></el-input>
            </el-form-item>
            <el-form-item  label="微信号" prop="">
              <el-input v-model="addOrUpdateForm.contactsWechat" placeholder="请填写联系人微信号"></el-input>
            </el-form-item>
            <el-form-item  label="法人代表" prop="">
              <el-input v-model="addOrUpdateForm.legalName" placeholder="请填写法人代表"></el-input>
            </el-form-item>
            <el-form-item label="法人联系方式" prop="">
              <el-input v-model="addOrUpdateForm.legalMobile"  placeholder="请填写法人手机号"></el-input>
            </el-form-item>
            <el-form-item label="企业地址" prop="">
              <el-input v-model="addOrUpdateForm.addressDetail"  placeholder="请填写企业地址"></el-input>
            </el-form-item>
            <el-form-item label="安许编号" prop="">
              <el-input v-model="addOrUpdateForm.securityLicenseCode"  placeholder="请填写安许编号"></el-input>
            </el-form-item>
            <el-form-item label="安许到期日期" prop="">
              <el-date-picker
                v-model="addOrUpdateForm.securityLicenseExpiryDate"
                style="width: 100%"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="请选择安许到期日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="安许证照图片" prop="">
              <el-upload
                list-type="picture-card"
                :headers="uploadHeader"
                :file-list="securityUploadFileList"
                :before-upload="handlePicUploadBefore"
                :on-success="handleSecurityPicUploadSuccess"
                :on-error="handlePicUploadError"
                :on-remove="handleSecurityPicUploadRemove"
                :on-exceed="handleExceed"
                :action="this.$http.adornUrl('/ent/customer/file/upload')"
                accept=".jpg,.png"
                :limit="1">
                <i class="el-icon-plus"></i>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过800kb</div>
              </el-upload>
              <!--            <el-input v-model="addOrUpdateForm.securityLicenseImageUrl"  placeholder="请填写企业地址"></el-input>-->
            </el-form-item>
            <el-form-item  label="备注" prop="">
              <el-input v-model="addOrUpdateForm.remark" type="textarea" placeholder="备注" :autosize="{ minRows: 2, maxRows: 4}" maxlength="100" show-word-limit></el-input>
            </el-form-item>
          </el-form>
          <div class="button-group">
            <el-button @click="clickCancel">返回</el-button>
            <el-button type="primary" @click="clickConfirm">保存</el-button>
          </div>
        </el-col>
      </el-row>
      <add-cooperation-dialog :id="customerId"  @dialogVisibleChange="cooperationDialogVisibleChange" :dialogVisible="addCooperationDialogVisible" ></add-cooperation-dialog>
    </div>
  </div>

</template>

<script>
import {
  mobileAndPhoneValidator,
  mobileValidator,
  certificateCodeValidator,
  repeatCertificateCodeValidator
} from '../../../../../utils/validate'
import Vue from 'vue'
import {matchQuali} from '../../../../../api/customer/commom'
import {getDetail, saveCustomer, updateCustomer} from '../../../../../api/customer/customerDetail'
import {getRegionTree} from '../../../../../api/customer/region'
import AddCooperationDialog from '../../Component/AddCooperationDialog'
import {addCoopetationDialogMixin} from '../../../../../mixin'
// import {checkRepeatNamePromise} from '../../../../../api/customer/personal'
const uniqBy = require('lodash/uniqBy')
export default {
  name: 'ent-add-or-update',
  mixins: [addCoopetationDialogMixin],
  components: {AddCooperationDialog},
  props: {
    title: {
      type: String,
      default: ''
    },
    isAdd: {
      type: Boolean,
      default: true
    },
    id: {
      type: Number,
      default: null
    }
  },
  created () {
    this.getRegionalTree()
    // this.setNoneQualiOption()
    if (!this.isAdd) {
      this.getDetail()
    }

    this.changeCertificateCodeRule(this.addOrUpdateFormRules)
  },
  data () {
/*    let certificateCodeValidator = (rule, value, callBack) => {
      if (value === '') {
        return callBack(new Error('请填写社会统一信用代码'))
      } else if (value.length !== 18) {
        return callBack(new Error('代码位数为18位，请检查后输入'))
      } else if (!isCertificateCode(value)) {
        return callBack(new Error('社会统一信用代码格式有误，请检查后输入'))
      } else {
        callBack()
      }
    }
    let mobileAndPhoneValidator = (rule, value, callBack) => {
      if (value !== '') {
        if (!isMobile(value) && !isPhone(value)) {
          return callBack(new Error('手机或电话号码格式有误，请检查后输入'))
        } else {
          callBack()
        }
      } else {
        callBack()
      }
    }

    let mobileValidator = (rule, value, callBack) => {
      if (value !== '') {
        if (!isMobile(value)) {
          return callBack(new Error('手机号码格式有误，请检查后输入'))
        } else {
          callBack()
        }
      } else {
        callBack()
      }
    } */
    return {
      loading: false,
      // 用于信用代码重复时添加合作记录的用户id
      customerId: '',
      dealRecords: [],
      qualiOptions: [],
      cityOptions: [],
      areaOptions: [],
      // 城市区域树形数据
      regionalTree: [],
      uploadFileList: [],
      securityUploadFileList: [],
      // 资质列表选项为'无'的Id
      noneQualiId: '',
      // 模糊匹配过的所有资质项
      qualiQueryedList: [],
      // typeId为3,enterpriseFlag为1
      addOrUpdateForm: {
        typeId: 3,
        enterpriseFlag: 1,
        name: '',
        cityId: '',
        areaId: '',
        certificateCode: '',
        qualiImageList: [],
        qualiIdList: [],
        contactsName: '',
        contactsPosition: '',
        contactsMobile: '',
        contactsWechat: '',
        legalName: '',
        legalMobile: '',
        addressDetail: '',
        securityLicenseCode: '',
        securityLicenseExpiryDate: '',
        securityLicenseImageUrl: '',
        remark: '',
        qualiNames: []
      },
      addOrUpdateFormRules: {
        name: [
          { required: true, message: '请填写企业名称', trigger: 'blur' }
        ],
        cityId: [
          { required: true, message: '请选择城市区域', trigger: 'blur' }
        ],
        areaId: [
          { required: true, message: '请选择城市区域', trigger: 'blur' }
        ],
/*        certificateCode: [
          { required: true, validator: certificateCodeValidator, trigger: 'blur' }
        ], */
        qualiIdList: [
          { required: true, message: '请选择/填写企业资质证书信息', trigger: 'blur' }
        ],
        qualiNames: [
          { required: true, message: '请选择/填写企业资质证书信息', trigger: 'blur' }
        ],
        contactsName: [
          { required: true, message: '请填写联系人姓名', trigger: 'blur' }
        ],
        contactsMobile: [
          { validator: mobileAndPhoneValidator, trigger: 'blur' }
        ],
        legalMobile: [
          { validator: mobileValidator, trigger: 'blur' }
        ]

      }
    }
  },
  watch: {
    // 主要用于修改时，获取并设置areaOptions
    'addOrUpdateForm.cityId': function (newValue, oldVal) {
      this.filterCityOptions(newValue)
    }
  },
  methods: {
    changeCertificateCodeRule (rules = {}) {
      if (this.isAdd) {
        rules['certificateCode'] = [
          { required: true, validator: repeatCertificateCodeValidator, trigger: 'blur' }
        ]
      } else {
        rules['certificateCode'] = [
          { required: true, validator: certificateCodeValidator, trigger: 'blur' }
        ]
      }
    },
    clickCancel () {
      if (this.isAdd) {
        this.$parent.changeComponent('potential-clients')
      } else {
        this.$parent.changeIsEditState(false)
      }
    },
    initAddorUpdateForm () {
      Object.keys(this.addOrUpdateForm).forEach((key) => {
        if (Array.isArray(this.addOrUpdateForm[key])) {
          this.addOrUpdateForm[key] = []
        } else {
          this.addOrUpdateForm[key] = ''
        }
      })
    },
    getDetail () {
      if (this.id && !this.isAdd) {
        this.loading = true
        getDetail(this.id,
          (data) => {
            this.addOrUpdateForm.name = data.data.name
            this.addOrUpdateForm.cityId = data.data.cityId
            this.addOrUpdateForm.areaId = data.data.areaId
            this.addOrUpdateForm.certificateCode = data.data.certificateCode
            this.addOrUpdateForm.qualiImageList = data.data.qualiImageList
            this.qualiOptions = data.data.qualiList
            this.qualiQueryedList = data.data.qualiList
            this.addOrUpdateForm.qualiIdList = this.getQualiIdList(data.data.qualiList)
            // this.addOrUpdateForm.qualiNames = this.getQualiNameList(data.data.qualiList)
            this.addOrUpdateForm.qualiNames = data.data.qualiList
            this.addOrUpdateForm.contactsName = data.data.contactsName
            this.addOrUpdateForm.contactsPosition = data.data.contactsPosition
            this.addOrUpdateForm.contactsMobile = data.data.contactsMobile
            this.addOrUpdateForm.contactsWechat = data.data.contactsWechat
            this.addOrUpdateForm.legalName = data.data.legalName
            this.addOrUpdateForm.legalMobile = data.data.legalMobile
            this.addOrUpdateForm.addressDetail = data.data.addressDetail
            this.addOrUpdateForm.remark = data.data.remark
            this.addOrUpdateForm.securityLicenseCode = data.data.securityLicenseCode
            this.addOrUpdateForm.securityLicenseExpiryDate = data.data.securityLicenseExpiryDate
            this.addOrUpdateForm.securityLicenseImageUrl = data.data.securityLicenseImageUrl
            this.setUploadFileList(data.data.qualiImageList)
            this.setSecurityUploadFileList(data.data.securityLicenseImageUrl)
            this.loading = false
          }, () => {
            this.loading = false
          })
      }
    },
    clickConfirm () {
      this.$refs['addOrUpdateFormRefs'].validate((valid) => {
        if (valid) {
          let dataForm = {
            'name': this.addOrUpdateForm.name,
            'cityId': this.addOrUpdateForm.cityId,
            'areaId': this.addOrUpdateForm.areaId,
            'certificateCode': this.addOrUpdateForm.certificateCode,
            'qualiImageList': this.addOrUpdateForm.qualiImageList,
            'qualiIdList': this.addOrUpdateForm.qualiIdList,
            'contactsName': this.addOrUpdateForm.contactsName,
            'contactsPosition': this.addOrUpdateForm.contactsPosition,
            'contactsMobile': this.addOrUpdateForm.contactsMobile,
            'contactsWechat': this.addOrUpdateForm.contactsWechat,
            'legalName': this.addOrUpdateForm.legalName,
            'legalMobile': this.addOrUpdateForm.legalMobile,
            'addressDetail': this.addOrUpdateForm.addressDetail,
            'remark': this.addOrUpdateForm.remark,
            'securityLicenseCode': this.addOrUpdateForm.securityLicenseCode,
            'securityLicenseExpiryDate': this.addOrUpdateForm.securityLicenseExpiryDate,
            'securityLicenseImageUrl': this.addOrUpdateForm.securityLicenseImageUrl
          }
          this.loading = true
          if (this.isAdd) {
            this.setQualiIdList()
            dataForm.typeId = 2
            dataForm.enterpriseFlag = 1
            saveCustomer(dataForm, () => {
              this.$message.success('添加成功!')
              this.initAddorUpdateForm()
              this.loading = false
            }, () => {
              this.loading = false
            })
          } else {
            // 修改接口
            if (this.id) {
              dataForm.id = this.id
              updateCustomer(dataForm,
                () => {
                  this.$message.success('修改成功!')
                  this.loading = false
                }, () => {
                  this.loading = false
                })
            }
          }
        } else {
          return false
        }
      })
    },
    // 将qualiImageList转化为uploa的中file-list的格式
    setUploadFileList (qualiImageList = []) {
      if (qualiImageList) {
        qualiImageList.forEach((item) => {
          let fileObj = {name: '', url: ''}
          fileObj.name = item.slice(item.lastIndexOf('/') + 1)
          fileObj.url = item
          this.uploadFileList.push(fileObj)
        })
      }
    },
    setSecurityUploadFileList (imageUrl = '') {
      if (imageUrl) {
        let fileObj = {name: '', url: ''}
        fileObj.name = imageUrl.slice(imageUrl.lastIndexOf('/') + 1)
        fileObj.url = imageUrl
        this.securityUploadFileList.push(fileObj)
      }
    },
    // 将数组转换成规定格式
    transformQualiTagList (qualiTagList = []) {
      let qualiTagStr = ''
      if (qualiTagList) {
        qualiTagStr = qualiTagList.join(',')
      }
      return qualiTagStr
    },
    // 获取资质id列表
    getQualiIdList (qualiList = []) {
      if (qualiList) {
        return qualiList.map(item => item.id)
      }
    },
    // 修改操作时，返回资质名称列表
    getQualiNameList (qualiList = []) {
      if (qualiList) {
        return qualiList.map(item => item.name)
      }
    },
    // 设置资质id列表
    setQualiIdList () {
      // eslint-disable-next-line no-unused-vars
      this.addOrUpdateForm.qualiIdList = this.addOrUpdateForm.qualiNames.map(item => item.id)
      /*      let selectedList = []
            this.addOrUpdateForm.qualiNames.forEach((qualiName) => {
              selectedList = selectedList.concat(this.qualiQueryedList.filter((qualiOption) =>
                qualiOption.name === qualiName
              ))
            })
            if (selectedList) {
              this.addOrUpdateForm.qualiIdList = this.unique(selectedList.map(item => item.id))
            } */
    },
    // 数组去重
    unique (arr) {
      return Array.from(new Set(arr))
    },
    // 资质列表获取无的选项，并添加至资质选择列表中
    setNoneQualiOption () {
      matchQuali(
        {'qualisContent': '无'},
        (data) => {
          this.qualiOptions.push(data.data[0])
          this.noneQualiId = data.data[0].id
          this.addOrUpdateForm.qualiIdList.push(this.noneQualiId)
        })
    },
    getRegionalTree () {
      let dataForm = {'actionId': 1}
      getRegionTree(dataForm, (data) => { this.cityOptions = data.data })
    },
    changeQualiOptions (option) {
      if (option) {
        const noneOption = option.filter((item) => item.name === '无')
        if (noneOption.length > 0) {
          this.addOrUpdateForm.qualiNames = [noneOption[0]]
          this.addOrUpdateForm.qualiIdList = [noneOption[0].id]
        } else {
          // 最新点击的选项
          let newSelectOption = option[option.length - 1]
          let oldSelectOption = {}
          let hasSameQualiCode = false
          for (let i = 0; i < option.length - 1; i++) {
            if (newSelectOption.qualiCode === option[i].qualiCode) {
              hasSameQualiCode = true
              oldSelectOption = option[i]
              break
            }
          }
          if (hasSameQualiCode) {
            this.$confirm(`同一类型的只能选择一个等级，选择的新资质"${newSelectOption.name}"与已选择的旧资质"${oldSelectOption.name}"冲突，是否替换？`, '提示', {
              confirmButtonText: '确认替换',
              cancelButtonText: '取消选择'
            }).then(() => {
              let oldIndex = this.addOrUpdateForm.qualiNames.findIndex((item) => item.id === oldSelectOption.id)
              this.addOrUpdateForm.qualiNames.splice(oldIndex, 1)
            }).catch(() => {
              let newIndex = this.addOrUpdateForm.qualiNames.findIndex((item) => item.id === newSelectOption.id)
              this.addOrUpdateForm.qualiNames.splice(newIndex, 1)
            })
          }
          this.setQualiIdList()
        }
      }
/*      // console.log('option:', option)
      if (option) {
        // 选择选项择清空Id列表
        for (let index = 0; index < option.length; index++) {
          if (option[index] === '无') {
            this.addOrUpdateForm.qualiIdList = []
            this.addOrUpdateForm.qualiIdList.push(this.noneQualiId)
            this.addOrUpdateForm.qualiNames = ['无']
            break
          }
        }
      }
      this.setQualiIdList() */
    },
    changeCityOptions (cityId) {
      this.addOrUpdateForm.areaId = ''
      this.filterCityOptions(cityId)
    },
    filterCityOptions (cityId) {
      // eslint-disable-next-line no-unused-vars
      let city = []
      this.areaOptions = []
      city = this.cityOptions.filter(item => item.id === cityId)
      if (city.length > 0) {
        this.areaOptions = city[0].children
      }
    },
    // 资历图片上传 监听函数
    handlePicUploadBefore (file) {
      let fileType = file.type
      let fileSize = file.size / 1024
      const isTypeRight = (fileType === 'image/png' || fileType === 'image/jpg' || fileType === 'image/jpeg')
      const isSizeRight = (fileSize / 1024 < 801)
      if (!isTypeRight) {
        this.$message.error('图片格式不正确，请重新上传！')
        return false
      } else if (!isSizeRight) {
        this.$message.error('图片不得超过800kb，请重新上传！')
        return false
      }
    },
    // 图片上传成功监听函数
    handlePicUploadSuccess (response, file, fileList) {
      let fileUrl = ''
      if (response.code === 0) {
        fileUrl = response.data.remoteUrl + response.data.fileName
        this.addOrUpdateForm.qualiImageList.push(fileUrl)
      } else {
        this.$message.error(response.msg)
      }
    },
    // 图片上传失败监听函数
    handlePicUploadError (err, file, fileList) {
      console.log('err', err)
      this.$message.error('上传失败请重试')
    },
    // 图片删除监听函数
    handlePicUploadRemove (file, fileList) {
      if (this.addOrUpdateForm.qualiImageList) {
        this.addOrUpdateForm.qualiImageList = this.addOrUpdateForm.qualiImageList.filter(item => item.indexOf(file.name) !== -1)
      }
    },
    // 图片上传成功监听函数
    handleSecurityPicUploadSuccess (response, file, fileList) {
      let fileUrl = ''
      if (response.code === 0) {
        fileUrl = response.data.remoteUrl + response.data.fileName
        this.addOrUpdateForm.securityLicenseImageUrl = fileUrl
      } else {
        this.$message.error(response.msg)
      }
    },
    // 图片删除监听函数
    handleSecurityPicUploadRemove (file, fileList) {
      this.addOrUpdateForm.securityLicenseImageUrl = ''
    },
    handleExceed (files, fileList) {
      this.$message.warning(`最多只能上传 1 张图片`)
    },
    remoteMethod (query) {
      if (query) {
        matchQuali(
          {'qualisContent': query},
          (data) => {
            if (data.data) {
              // 将搜索的结果与选中的结果合并，防止select选项内容空白
              let options = data.data.concat(this.addOrUpdateForm.qualiNames)
              this.qualiOptions = uniqBy(options, 'id')
              this.qualiQueryedList = this.qualiQueryedList.concat(data.data)
            }
          }
        )
      }
    }
/*    async validateHandle (prop, valida, err) {
      // 使用校验字段和错误信息确定是信用代码重复，再弹出确定对话框
      if (prop === 'certificateCode' && err === '社会统一信用代码重复') {
        let code = this.addOrUpdateForm.certificateCode
        await checkRepeatNamePromise({'id': '',
          'certificateCode': code,
          'name': ''}).catch((data) => {
            if (data.code === 600) {
              this.customerId = data.data
              this.$confirm(data.msg, '提示', {
                confirmButtonText: '确认添加',
                cancelButtonText: '取消添加'
              }).then(() => {
                this.addCooperationDialogVisible = true
              })
            }
          })
      }
    } */
  },
  computed: {
    uploadHeader () {
      return {
        'token': Vue.cookie.get('token')
      }
    }
  }
}
</script>

<style lang='less' scoped>
.div-e {
  width: 100%;
  background-color: #FFFFFF;
  padding: 15px;

}
.in-ts {
  width: 5px;
  height: 18px;
  float: left;
  margin-right: 8px;
  background: #6E92E9;
}

.in-t {
  margin-bottom: 15px;
}

.select-button-group{
  display: flex;
  .el-select{
    flex: 1;
    margin-right: 10px;
  }
}

.button-group{
  display: flex;
  justify-content: center;
}
</style>
